<?php
class ItsStocksOutController extends AppController {
    var $name = 'ItsStocksOut';

    var $pageTitle = 'Stock out Information';

    var $viewPath = 'its/returns/stocks_out';

    var $uses = array('ItsStockOutHead', 'Product', 'RunningNo', 'ItsStockOut', 'ProductSerial', 'Warehouse');

    var $paginate = array(
            'order' => 'ItsStockOutHead.id DESC'
    );

    function beforeFilter() {
        parent::beforeFilter();
        $this->set('parentNav', 'its_returns');
        $this->set('tabMenu', 'tabmenus/its/returns');
    }

    function display() {
        parent::display();

        $op = array(
                'stock_out_no' => 'LIKE',
        );

        $this->_checkBetweenSearch('ItsStockOutHead', 'stock_out_date');

        $this->_paging('ItsStockOutHead', $op);
    }

    function save() {
        $its_stock_out_head_id = null;
        if (!empty($this->data)) {
            if ($this->data['mode'] == 'add') {
                $its_stock_out_head_id = $this->_save_stock_out();
            } else {
                $its_stock_out_head_id = $this->_edit_stock_out();
            }
        }
        $this->setAction('view', $its_stock_out_head_id);
    }

    function _edit_stock_out() {
        $stock_out_id = $this->data['ItsStockOutHead']['id'];
        $this->ItsStockOutHead->id = $stock_out_id;
        if ($this->ItsStockOutHead->saveField('remark', $this->data['ItsStockOutHead']['remark'])) {
            $this->Session->setFlash("Edit dispatch succesfull.", 'flash/ok');
        } else {
            $this->Session->setFlash("Edit dispatch fail.", 'flash/fail');
        }
        return $stock_out_id;
    }

    function _save_stock_out() {
        $its_stock_out_head_id = null;
        $is_success = true;
        $collector_id = $this->Session->read('Auth.User.id');

        // เรียงลำดับรายการใหม่ กรณีลบแถว Index เปลี่ยน
        $this->adjustRowIndex($this->data['ItsStockOut']);

        // ตรวจสอบว่ามีสินค้าอยู่ในใบ ItsStockInHead
        if(count($this->data['ItsStockOut']) == 0) {
            $this->Session->setFlash("Stock out must have at least one product !!!.", 'flash/fail');
        } else {

            $this->ItsStockOutHead->query("BEGIN");

            $year = $this->Utility->getThaiYear();
            $runno = $this->RunningNo->getNextStockNo(RunningNo::ITS_STOCK_OUT_TYPE, $year);
            $this->data['ItsStockOutHead']['stock_out_no'] = ItsStockOutHead::STOCK_OUT_PREFIX . $year . $runno;
            $this->data['ItsStockOutHead']['stock_out_date'] = date('Y-m-d');
            $this->data['ItsStockOutHead']['collector_id'] = $collector_id;

            // Save ItsStockOutHead && ItsStockOut
            if($this->ItsStockOutHead->saveAll($this->data, array('validate' => 'first', 'atomic' => false))) {
                $its_stock_out_head_id = $this->ItsStockOutHead->id;

                // Update Product current stock
                foreach($this->data['ItsStockOut'] as $itsStockOut) {
                    $product_id = $itsStockOut['product_id'];
                    $this->Product->id = $product_id;
                    $qty = $itsStockOut['qty'];
                    $current_stock = $this->Product->field('current_stock') - $qty;
                    $is_success &= $this->Product->saveField('current_stock', $current_stock);
                    $is_success &= $this->Product->saveField('last_stock_out_date', date('Y-m-d'));

                    //ดึงรายการ Cust stock in
                    $this->ItsStockOut->contain();
                    $si = $this->ItsStockOut->find('first',
                            array(
                            'conditions' => array(
                                    'its_stock_out_head_id' => $its_stock_out_head_id,
                                    'product_id' => $product_id
                            ),
                            'fields' => array('id')
                            )
                    );

                    // หา product serial ที่มี SoP ต่ำสุด ที่ยังไม่ได้ Stock out / Dispatch
                    $this->ProductSerial->contain('Location');
                    $productSerials = $this->ProductSerial->find('all', array(
                            'conditions' => array(
                                    'product_id' => $product_id,
                                    'its_stock_out_id' => null,
                                    'Location.warehouse_id' => $this->data['ItsStockOutHead']['warehouse_id']
                            ),
                            'fields' => array('id'),
                            'order' => array('stock_out_priority ASC'),
                            'limit' => $qty
                            )
                    );

                    // update รายการ Product Serial
                    foreach ($productSerials as $ps) {
                        $data = array();
                        $data['ProductSerial']['id'] = $ps['ProductSerial']['id'];
                        $data['ProductSerial']['its_stock_out_id'] = $si['ItsStockOut']['id'];
                        $data['ProductSerial']['its_stock_out_type'] = ItsStockOut::ITS_STOCK_OUT_TYPE;
                        $this->ProductSerial->create();
                        $this->ProductSerial->save($data);
                    }
                }
            } else {
                $is_success = false;
            }
            if ($is_success) {
                $this->ItsStockOutHead->query("COMMIT");
                $its_stock_out_head_id = $this->ItsStockOutHead->id;
                $this->Session->setFlash("ItsStockOutHead no {$this->data['ItsStockOutHead']['stock_out_no']} save succesfull.", 'flash/ok');
            } else {
                $this->ItsStockOutHead->query("ROLLBACK");
                $this->Session->setFlash("ItsStockOutHead no save fail!!!.", 'flash/fail');
            }
        }
        $this->data['ItsStockOut'] = null;
        return $its_stock_out_head_id;
    }

    function view($id = null) {
        if ($id != null) {
            $this->ItsStockOutHead->contain(array('Warehouse', 'User', 'ItsStockOut' => array('Product' => array('part_no', 'text', 'Unit'))));
            $this->data = $this->ItsStockOutHead->findById($id);

            $this->_neighbors($id, $this->ItsStockOutHead, array('fields' => array('id', 'stock_out_no')));
            $this->set('mode', 'edit');
        } else {
            $this->set('warehouses', $this->Warehouse->find('list'));
            $this->set('mode', 'add');
        }
    }

    function print_view($id) {
        $this->layout = 'print';
        $this->data = $this->ItsStockOutHead->findForPrintById($id);
    }

    function popup_search() {
        parent::popup_search();

        $this->set('warehouses', $this->Warehouse->find('list', array('fields' => array('id', 'name'))));
        $this->set('popupWidth', 500);
    }

    /**
     * ค้นหา Product จาก part no และ warehouse ที่เลือก
     * @param string $part_no
     * @param int $warehouse_id
     */
    function json_find_by_part_no_warehouse_id() {
        $this->layout = 'ajax';
        $data = $this->Product->find('first', array(
                'conditions' => array(
                        'Product.part_no' => $this->data['part_no'],
                ))
        );

        // ถ้ามีข้อมูล หาจำนวน current_stock ที่อยู่ใน Warehouse ที่เลือก
        if ($data != false) {
            $data['Product']['current_stock'] = $this->ProductSerial->find('count', array(
                    'conditions' => array(
                            'Location.warehouse_id' => $this->data['warehouse_id'],
                            'ProductSerial.product_id' => $data['Product']['id'],
                            'ProductSerial.its_stock_out_id' => null
                    ))
            );
        }

        $this->set('data', $data);
        // view เก็บอยู่ใน element
        $this->viewPath = 'elements';
        $this->render('ajax/json');
    }
}
?>
